<?php
/**
 *  TinyMVC - TinyMVCModelAndView.class.php file
 *
 * @author Adrian Wieczorek <adi(at)tinymvc(dot)org>
 * @package TinyMVC
 * @version $Id: TinyMVCModelAndView.class.php 57 2008-11-07 08:43:14Z adi3ek $
 *
 */

/**
 * Model and View transfer object class
 * @package TinyMVC
 */
class TinyMVCModelAndView {
	/**
	 * Model
	 * @access private
	 * @var TinyMVCResource
	 */
	private $model;
	/**
	 * flag indicating custom Model to be used
	 * @access private
	 * @var bool
	 */
	private $isCustomModel = false;
	/**
	 * View
	 * @access private
	 * @var TinyMVCResource
	 */
	private $view;

	/**
	 * @param TinyMVCView $view view object
	 * @param TinyMVCResource $model custom model object (optional)
	 * @param bool $isCustomModel true for custom Model support
	 */
	public function __construct(TinyMVCView $view, TinyMVCResource $model = null, $isCustomModel = false) {
		if($model == null) {
			// initialize standard TinyMVC Model Resource
			$this->model = new TinyMVCResource('model');
			$this->model->elements = new TinyMVCSimpleContainer;
		}
		else {
			$this->setModel($model, $isCustomModel);
		}

		$this->view = $view;
	}

	/**
	 * get Model
	 * @return TinyMVCResource Model container
	 */
	public function getModel() {
		return $this->model;
	}

	/**
	 * set Model
	 * @param TinyMVCResource $model Model container
	 * @param bool $isCustomModel flag indicating custom Model to be set
	 */
	public function setModel(TinyMVCResource $model, $isCustomModel = false) {
		$this->isCustomModel = $isCustomModel;
		$this->model = $model;
	}
	
	/**
	 * true if custom Model resource in use
	 * @return bool 
	 */
	public function isCustomModel() {
		return $this->isCustomModel;
	}

	/**
	 * get View
	 * @return TinyMVCView View container
	 */
	public function getView() {
		return $this->view;
	}

	/**
	 * set View
	 * @param TinyMVCView $view View container
	 */
	public function setView(TinyMVCResource $view) {
		$this->view = $view;
	}

	/**
	 * merge with another modelAndView transfer object
	 * @param TinyMVCModelAndView $modelAndView modelAndView to merge
	 */
	public function merge(TinyMVCModelAndView $modelAndView) {
		// merging Model, if it's not custom
		if(!$this->isCustomModel) {
			foreach($modelAndView->getModel()->getElements() as $key => $value) {
				$this->model->addElement($key, $value);
			}
		}

		// merging view
		foreach($modelAndView->getView()->getElements() as $key => $element) {
			// we don't wana do resolving process, because it's already done.
			$this->view->addElement($key, $element, false);
		}
	}
}
